/*
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Utils.java
 * Copyright (C) 2017 University of Waikato, Hamilton, NZ
 */

package cn.myzf.fort.access.accesscommon.core;

import org.apache.commons.lang.SystemUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * Various helper methods.
 *
 * @author FracPete (fracpete at waikato dot ac dot nz)
 * @version $Revision$
 */
public class Utils {

  /**
   * Flattens the list.
   *
   * @param parts	the list to flatten
   * @param sep		the separator to use
   * @return		the flattened array
   */
  public static String flatten(List parts, String sep) {
    Object[]	array;
    int		i;

    array = new Object[parts.size()];
    for (i = 0; i < parts.size(); i++)
      array[i] = parts.get(i);

    return flatten(array, sep);
  }

  /**
   * Flattens the array.
   *
   * @param parts	the array to flatten
   * @param sep		the separator to use
   * @return		the flattened array
   */
  public static String flatten(Object[] parts, String sep) {
    StringBuilder	result;
    int			i;

    result = new StringBuilder();
    for (i = 0; i < parts.length; i++) {
      if (i > 0)
	result.append(sep);
      result.append(parts[i].toString());
    }

    return result.toString();
  }

  protected static void exec(String command, boolean close) {

    try {
      // 执行命令
      Process process = Runtime.getRuntime().exec(command);
      process.getInputStream().close();
      process.getErrorStream().close();
      process.getOutputStream().close();
      process.waitFor(5, TimeUnit.SECONDS);
      if (close) {
        process.destroy();
      }
    } catch (IOException | InterruptedException e) {

    }
  }

  //判断是否为数字型字符串
  public static boolean isInteger(String str) {
    Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
    return pattern.matcher(str).matches();
  }


  //判断代理是否已开启了
  public static String checkListening(String dynamicSock5PortForward) throws IOException {
    /*判断是否正常启动起来*/
    ProcessBuilder builder = new ProcessBuilder();
    List<String> commands = new ArrayList<>();

    commands.add("cmd");
    commands.add("/c");
    if (SystemUtils.IS_OS_WINDOWS)
      commands.add(String.format("netstat -ano|findstr %s | findstr LISTENING ",dynamicSock5PortForward));
    else if (SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC_OSX)
      commands.add(String.format("netstat -ano|grep %s | grep LISTENING ",dynamicSock5PortForward));
    String[] cmd = commands.toArray(new String[]{});

    builder.command(cmd);

    Process process = builder.start();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()), 1024);
    String stout = bufferedReader.readLine();
    if (stout!=null) {
      String [] arr = stout.split("\\s+");
      return arr[5];
    }
    return "";
  }

  public static void killProcess(String pid) {
    if (isInteger(pid)){
      String command = String.format("taskkill /F /PID %s",pid);
      exec(command, true);
    }
  }
}
